package com.hctforgreen.greenservice.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;

/**
 * 图片处理类
 * 
 * @author Administrator
 * 
 */
public class BitmapUtil {

	/**
	 * 通过资源id转换成bitmap
	 * 
	 * @param res
	 *            资源
	 * @param resourid
	 *            资源id
	 * @param scale
	 *            转换大小
	 * @return
	 */
	public static Bitmap getBitmap(Resources res, int resourid, int scale) {
		Options op = new Options();
		op.inSampleSize = scale;
		return BitmapFactory.decodeResource(res, resourid, op);
	}

	/**
	 * 通过资源id转换成bitmap
	 * 
	 * @param res
	 *            资源
	 * @param resourid
	 *            资源id
	 * @param width
	 *            宽度
	 * @param height
	 *            高度
	 * @return
	 */
	public static Bitmap getBitmap(Resources res, int resourid, int width,
			int height) {
		Options op = new Options();
		op.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(res, resourid, op);
		int x = op.outHeight / height;
		int y = op.outWidth / width;
		return getBitmap(res, resourid, x > y ? x : y);
	}

	/**
	 * 通过图片路径转换成bitmap
	 * 
	 * @param pathName
	 *            路径
	 * @param scale
	 *            转换大小
	 * @return
	 */
	public static Bitmap getBitmap(String pathName, int scale) {
		Options op = new Options();
		op.inSampleSize = scale;
		return BitmapFactory.decodeFile(pathName, op);
	}

	/**
	 * 通过图片路径转换成bitmap
	 * 
	 * @param pathName
	 *            路径
	 * @param width
	 *            宽度
	 * @param height
	 *            高度
	 * @return
	 */
	public static Bitmap getBitmap(String pathName, int width, int height) {
		Options op = new Options();
		op.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, op);
		int x = op.outHeight / height;
		int y = op.outWidth / width;
		return getBitmap(pathName, x > y ? x : y);
	}

	/**
	 * 二进制转换成bitmap
	 * 
	 * @param data
	 *            byte[]
	 * @param scale
	 *            转换大小
	 * @return
	 */
	public static Bitmap getBitmap(byte[] data, int scale) {
		if (scale < 1)
			scale = 1;
		Options op = new Options();
		op.inSampleSize = scale;
		return BitmapFactory.decodeByteArray(data, 0, data.length, op);
	}

	/**
	 * 二进制转换成bitmap
	 * 
	 * @param data
	 *            byte[]
	 * @param width
	 *            宽度
	 * @param height
	 *            高度
	 * @return
	 */
	public static Bitmap getBitmap(byte[] data, int width, int height) {
		Options op = new Options();
		op.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, op);
		int x = op.outHeight / height;
		int y = op.outWidth / width;
		return getBitmap(data, x > y ? x : y);
	}

	/**
	 * 图片圆角处理
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		try {
			Paint p = new Paint();
			p.setColor(Color.WHITE);
			p.setStrokeWidth(8);
			p.setStyle(Paint.Style.STROKE);
			p.setAntiAlias(true);
			Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(),
					bitmap.getHeight(), Config.ARGB_8888);
			Canvas canvas = new Canvas(outBitmap);
			final int color = 0xff424242;
			final Paint paint = new Paint();
			final Rect rect = new Rect(0, 0, bitmap.getWidth(),
					bitmap.getHeight());
			final RectF rectF = new RectF(rect);
			final float roundPX = bitmap.getWidth() / 2;
			paint.setAntiAlias(true);
			canvas.drawARGB(0, 0, 0, 0);
			paint.setColor(color);
			canvas.drawRoundRect(rectF, roundPX, roundPX, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(bitmap, rect, rect, paint);
			canvas.drawCircle(rect.centerX(), rect.centerY(),
					rect.width() / 2 - 2, p);
			return outBitmap;
		} catch (OutOfMemoryError err) {
			// TODO: handle exception
		}
		return bitmap;
		// return BitmapFactory.decodeResource(c.getResources(),
		// R.drawable.head_pic_default);
	}

	/**
	 * 圆角位图
	 * 
	 * @param bitmap
	 * @param rectSize
	 *            圆角大小
	 * @return
	 */
	public static Bitmap getRectBitmap(Bitmap bitmap, int rectSize) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		final float roundPx = rectSize;// 圆角大小
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		if (bitmap != null && !bitmap.isRecycled()) {
			bitmap.recycle();
			bitmap = null;
		}
		return output;
	}

	/**
	 * bitmap保存成文件
	 * 
	 * @param path
	 *            //路径
	 * @param bitmap
	 */
	public static void save(String path, Bitmap bitmap) {
		try {
			File file = new File(path);
			if (!file.getParentFile().exists())
				file.getParentFile().mkdirs();
			if (!file.exists())
				file.createNewFile();
			FileOutputStream fs = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 100, fs);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * bitmap质量压缩
	 */
	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	/**
	 * 按比例大小压缩
	 * 
	 * @param srcPath
	 * @return
	 */
	public static Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是1280*720分辨率，所以高和宽我们设置为
		float hh = 1280f;// 这里设置高度为1280f
		float ww = 720f;// 这里设置宽度为720f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 等比缩放
	 * 
	 * @param image
	 * @return
	 */
	public static Bitmap comp(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是1280*720分辨率，所以高和宽我们设置为
		float hh = 1280f;// 这里设置高度为1280f
		float ww = 720f;// 这里设置宽度为720f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/**
	 * 压缩图片
	 */
	public static String zipPhoto(final String photoFile) {
		if (photoFile == null || photoFile.trim().length() == 0) {
			return "";
		}
		File file = new File(photoFile);
		if (!file.exists()) {
			return "";
		}
		File resFile = new File(HctConstants.DEFAULT_ROOT_PATH
				+ HctConstants.DEFAULT_IMG_STORE_PATH + file.getName());
		try {
			if (resFile.getParentFile() == null
					|| !resFile.getParentFile().exists()) {
				resFile.getParentFile().mkdirs();
			}
			if (!resFile.exists()) {
				resFile.createNewFile();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// BitmapFactory.Options options = new BitmapFactory.Options();
		// if (file.length() > 10 * 1024 * 1024) {
		// options.inSampleSize = 30;
		// } else if (file.length() > 6 * 1024 * 1024) {
		// options.inSampleSize = 20;
		// } else if (file.length() > 2 * 1024 * 1024) {
		// options.inSampleSize = 10;
		// } else if (file.length() > 1024 * 1024) {
		// options.inSampleSize = 5;
		// } else if (file.length() > 1024 * 512) {
		// options.inSampleSize = 2;
		// } else {
		// options.inSampleSize = 1;
		// }
		Bitmap bmp = comp(getimage(photoFile));
		try {
			bmp.compress(CompressFormat.JPEG, 100,
					new FileOutputStream(resFile));
			// FileOutputStream fos = new FileOutputStream(resFile);
			// fos.write(baos.toByteArray());
			// fos.flush();
			// fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resFile.getAbsolutePath();

	}

	/**
	 * 旋转图片
	 * 
	 * @param bitmap
	 * @param degress
	 * @return
	 */
	public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
		if (bitmap != null) {
			Matrix m = new Matrix();
			m.postRotate(degress);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), m, true);
			return bitmap;
		}
		return bitmap;
	}

	/**
	 * 获取图片旋转角度
	 * 
	 * @param path
	 * @return
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}
}
